﻿using Dragon.Library.Utility.NHibernate;
using NHibernate;

namespace Dragon.Library.Framework.Dao
{
    public partial class BaseDao<T, TKeyT>
    {
        public object Create(T bean)
        {
            ISession session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            object o = session.Save(bean);
            if (IsTran == false)
                session.Flush();
            return o;
        }

        public bool Update(T bean)
        {
            ISession session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            session.Update(bean);
            if (IsTran == false)
                session.Flush();
            return true;
        }

        public T GetObjectByKey(TKeyT id)
        {
            ISession session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            return session.Get<T>(id);
        }

        public bool Delete(T bean)
        {
            ISession session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            session.Delete(bean);
            if (IsTran == false)
                session.Flush();
            return true;
        }

        public void Flush()
        {
            try
            {
                if (Session.Transaction.IsActive)
                    Session.Transaction.Commit();
            }
            finally
            {
                if (Session.Transaction.IsActive)
                    Session.Transaction.Rollback();
            }
        }
    }
}
